package com.yunbao.main.views;

import android.content.Context;
import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yunbao.common.CommonAppConfig;
import com.yunbao.common.activity.AbsActivity;
import com.yunbao.common.adapter.ViewPagerAdapter;
import com.yunbao.common.bean.LevelBean;
import com.yunbao.common.event.UpdateFieldEvent;
import com.yunbao.common.glide.ImgLoader;
import com.yunbao.common.http.CommonHttpConsts;
import com.yunbao.common.http.CommonHttpUtil;
import com.yunbao.common.http.HttpCallback;
import com.yunbao.common.utils.CommonIconUtil;
import com.yunbao.common.utils.ToastUtil;
import com.yunbao.common.views.AbsLivePageViewHolder;
import com.yunbao.live.activity.LiveAudienceActivity;
import com.yunbao.live.bean.LiveBean;
import com.yunbao.live.bean.SearchUserBean;
import com.yunbao.live.event.LiveRoomChangeEvent;
import com.yunbao.live.http.LiveHttpUtil;
import com.yunbao.live.presenter.LiveCheckLivePresenter;
import com.yunbao.live.views.AbsUserHomeViewHolder;
import com.yunbao.main.R;
import com.yunbao.main.activity.EditProfileActivity;
import com.yunbao.main.activity.UserHomeActivity;
import com.yunbao.main.http.MainHttpConsts;
import com.yunbao.main.http.MainHttpUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

// +----------------------------------------------------------------------
// | Created by Yunbao
// +----------------------------------------------------------------------
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: https://gitee.com/yunbaokeji/
// +----------------------------------------------------------------------
// | Date: 2022-02-17
// +----------------------------------------------------------------------
/**
 * 用户个人主页
 */

public class UserHomeViewHolder extends AbsLivePageViewHolder{

    private static final int PAGE_COUNT = 1;
    private UserHomeDetailViewHolder mDetailViewHolder;
    private AbsUserHomeViewHolder[] mViewHolders;
    private List<FrameLayout> mViewList;
    private ImageView mAvatarBg;
    private ImageView mAvatar;
    private TextView mName;
    private ImageView mSex;
    private ImageView mLevelAnchor;
    private ImageView mLevel;
    private TextView mID;
    private View mBtnLive;
    private ViewPager mViewPager;

    private String mToUid;
    private boolean mFromLiveRoom;
    private String mFromLiveUid;
    private boolean mSelf;
    private SearchUserBean mSearchUserBean;
    private boolean mIsUpdateField;
    private boolean mPaused;
    private LiveCheckLivePresenter mCheckLivePresenter;


    public UserHomeViewHolder(Context context, ViewGroup parentView, String toUid, boolean fromLiveRoom, String fromLiveUid) {
        super(context, parentView, toUid, fromLiveRoom, fromLiveUid);
    }

    @Override
    protected void processArguments(Object... args) {
        mToUid = (String) args[0];
        if (args.length > 1) {
            mFromLiveRoom = (boolean) args[1];
        }
        if (args.length > 2) {
            mFromLiveUid = (String) args[2];
        }
        if (!TextUtils.isEmpty(mToUid)) {
            mSelf = mToUid.equals(CommonAppConfig.getInstance().getUid());
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.view_live_user_home_2;
    }

    @Override
    public void init() {
        setStatusHeight();
        super.init();
        if (mSelf) {
            View btnEdit = findViewById(R.id.btn_edit);
            btnEdit.setVisibility(View.VISIBLE);
            btnEdit.setOnClickListener(this);
        }
        mAvatarBg = (ImageView) findViewById(R.id.bg_avatar);
        mAvatar = (ImageView) findViewById(R.id.avatar);
        mName = (TextView) findViewById(R.id.name);
        mSex = (ImageView) findViewById(R.id.sex);
        mLevelAnchor = (ImageView) findViewById(R.id.level_anchor);
        mLevel = (ImageView) findViewById(R.id.level);
        mID = (TextView) findViewById(R.id.id_val);
        mBtnLive = findViewById(R.id.btn_live);

        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        if (PAGE_COUNT > 1) {
            mViewPager.setOffscreenPageLimit(PAGE_COUNT - 1);
        }
        mViewHolders = new AbsUserHomeViewHolder[PAGE_COUNT];
        mViewList = new ArrayList<>();
        for (int i = 0; i < PAGE_COUNT; i++) {
            FrameLayout frameLayout = new FrameLayout(mContext);
            frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            mViewList.add(frameLayout);
        }
        mViewPager.setAdapter(new ViewPagerAdapter(mViewList));
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                loadPageData(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        mBtnLive.setOnClickListener(this);
        findViewById(R.id.btn_back).setOnClickListener(this);

        EventBus.getDefault().register(this);
    }


    private void loadPageData(int position) {
        if (mViewHolders == null) {
            return;
        }
        AbsUserHomeViewHolder vh = mViewHolders[position];
        if (vh == null) {
            if (mViewList != null && position < mViewList.size()) {
                FrameLayout parent = mViewList.get(position);
                if (parent == null) {
                    return;
                }
                if (position == 0) {
                    mDetailViewHolder = new UserHomeDetailViewHolder(mContext, parent, mToUid, mSelf);
                    vh = mDetailViewHolder;
                }
                if (vh == null) {
                    return;
                }
                mViewHolders[position] = vh;
                vh.addToParent();
                vh.subscribeActivityLifeCycle();
            }
        }
        if (vh != null) {
            vh.loadData();
        }
    }

    @Override
    public void loadData() {
        if (TextUtils.isEmpty(mToUid)) {
            return;
        }
        loadPageData(0);
        MainHttpUtil.getUserHome(mToUid, new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String[] info) {
                if (code == 0 && info.length > 0) {
                    JSONObject obj = JSON.parseObject(info[0]);
                    SearchUserBean userBean = JSON.toJavaObject(obj, SearchUserBean.class);
                    mSearchUserBean = userBean;
                    String avatar = userBean.getAvatar();
                    ImgLoader.displayBlur(mContext, avatar, mAvatarBg);
                    ImgLoader.displayAvatar(mContext, avatar, mAvatar);
                    String toName = userBean.getUserNiceName();
                    mName.setText(toName);
                    mSex.setImageResource(CommonIconUtil.getSexIcon(userBean.getSex()));
                    CommonAppConfig appConfig = CommonAppConfig.getInstance();
                    LevelBean levelAnchor = appConfig.getAnchorLevel(userBean.getLevelAnchor());
                    ImgLoader.display(mContext, levelAnchor.getThumb(), mLevelAnchor);
                    LevelBean level = appConfig.getLevel(userBean.getLevel());
                    ImgLoader.display(mContext, level.getThumb(), mLevel);
                    mID.setText("ID:"+userBean.getId());

                    if (mDetailViewHolder != null) {
                        mDetailViewHolder.showData(userBean, obj);
                    }
                    if (mBtnLive != null) {
                        if (obj.getIntValue("islive") == 1) {
                            if (mBtnLive.getVisibility() != View.VISIBLE) {
                                mBtnLive.setVisibility(View.VISIBLE);
                            }
                        } else {
                            if (mBtnLive.getVisibility() == View.VISIBLE) {
                                mBtnLive.setVisibility(View.INVISIBLE);
                            }
                        }
                    }



                } else {
                    ToastUtil.show(msg);
                }
            }
        });
    }





    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i != R.id.btn_back && i != R.id.btn_live) {
            if (!((AbsActivity) mContext).checkLogin()) {
                return;
            }
        }
        if (i == R.id.btn_back) {
            back();

        } else if (i == R.id.btn_edit) {
            if (mContext != null) {
                mContext.startActivity(new Intent(mContext, EditProfileActivity.class));
            }
        } else if (i == R.id.btn_live) {
            forwardLiveRoom();
        }
    }

    private void back() {
        if (mContext instanceof UserHomeActivity) {
            ((UserHomeActivity) mContext).onBackPressed();
        }
    }




    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateFieldEvent(UpdateFieldEvent e) {
        if (mSelf) {
            mIsUpdateField = true;
        }
    }



    /**
     * 跳转到直播间
     */
    private void forwardLiveRoom() {
        if (mFromLiveRoom && !TextUtils.isEmpty(mFromLiveUid) && mToUid.equals(mFromLiveUid)) {
            ((UserHomeActivity) mContext).onBackPressed();
            return;
        }
        if (mSearchUserBean == null) {
            return;
        }
        LiveHttpUtil.getLiveInfo(mSearchUserBean.getId(), new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String[] info) {
                if (code == 0 && info.length > 0) {
                    LiveBean liveBean = JSON.parseObject(info[0], LiveBean.class);

                    if (mCheckLivePresenter == null) {
                        mCheckLivePresenter = new LiveCheckLivePresenter(mContext, new LiveCheckLivePresenter.ActionListener() {
                            @Override
                            public void onLiveRoomChanged(LiveBean liveBean, int liveType, int liveTypeVal) {
                                if (liveBean == null) {
                                    return;
                                }
                                if (mFromLiveRoom) {
                                    ((UserHomeActivity) mContext).onBackPressed();
                                    EventBus.getDefault().post(new LiveRoomChangeEvent(liveBean, liveType, liveTypeVal));
                                } else {
                                    LiveAudienceActivity.forward(mContext, liveBean, liveType, liveTypeVal, "", 0);
                                }
                            }
                        });
                    }
                    mCheckLivePresenter.checkLive(liveBean);
                }
            }
        });
    }


    @Override
    public void release() {
        super.release();
        EventBus.getDefault().unregister(this);
        if (mCheckLivePresenter != null) {
            mCheckLivePresenter.cancel();
        }
        mCheckLivePresenter = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        MainHttpUtil.cancel(MainHttpConsts.GET_USER_HOME);
        CommonHttpUtil.cancel(CommonHttpConsts.SET_ATTENTION);
        MainHttpUtil.cancel(MainHttpConsts.SET_BLACK);
    }

    @Override
    public void onPause() {
        mPaused = true;
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mSelf && mPaused) {
            if (mIsUpdateField) {
                mIsUpdateField = false;
                refreshUserInfo();
            }
        }
        mPaused = false;
    }

    /**
     * 刷新用户信息
     */
    private void refreshUserInfo() {
        if (TextUtils.isEmpty(mToUid)) {
            return;
        }
        MainHttpUtil.getUserHome(mToUid, new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String[] info) {
                if (code == 0 && info.length > 0) {
                    JSONObject obj = JSON.parseObject(info[0]);
                    SearchUserBean userBean = JSON.toJavaObject(obj, SearchUserBean.class);
                    mSearchUserBean = userBean;
                    String avatar = userBean.getAvatar();
                    ImgLoader.displayBlur(mContext, avatar, mAvatarBg);
                    ImgLoader.displayAvatar(mContext, avatar, mAvatar);
                    String toName = userBean.getUserNiceName();
                    mName.setText(toName);
                    mSex.setImageResource(CommonIconUtil.getSexIcon(userBean.getSex()));
                    mID.setText("ID"+userBean.getId());
                    if (mDetailViewHolder != null) {
                        mDetailViewHolder.refreshData(userBean, obj);
                    }
                    if (mBtnLive != null) {
                        if (obj.getIntValue("islive") == 1) {
                            if (mBtnLive.getVisibility() != View.VISIBLE) {
                                mBtnLive.setVisibility(View.VISIBLE);
                            }
                        } else {
                            if (mBtnLive.getVisibility() == View.VISIBLE) {
                                mBtnLive.setVisibility(View.INVISIBLE);
                            }
                        }
                    }

                } else {
                    ToastUtil.show(msg);
                }
            }
        });
    }

}
